package javase2.day07;
/**
 * 同步互斥的方法
 *
 */
public class Demo2 {
	public static void main(String[] args){
		final Stack stack = new Stack();
		//stack.push(5); 
		//stack.push(9);
		//System.out.println(stack.pop());
		new Thread(){
			public void run(){
				stack.push(5);
				System.out.println(stack.pop());
				System.out.println(stack.size());
			}
		}.start();
		new Thread(){
			public void run(){
				stack.push(10);
				System.out.println(stack.pop());
			}
		}.start();
	}
}
class Stack{
	Object[] buf = new Object[10];
	int top=0;
	public synchronized Object pop(){
		System.out.println("start pop");
		Object val = buf[--top];
		try{Thread.sleep(100);}catch(Exception e){e.printStackTrace();}
		buf[top]=null;
		System.out.println("over pop");
		return val;
	}
	public synchronized void push(Object obj){
		System.out.println("start push");
		buf[top++]=obj;
		try {
			Thread.sleep(100);
		} catch (Exception e) {
			// TODO: handle exception
		}
		System.out.println("over push");
	}
	public synchronized int size(){
		return top;
	}
}
class StringBuffer{
	char[] buf = new char[32];
	int size=0;
	public synchronized StringBuffer append(char ch){
		buf[size++]=ch;
		return this;
	}
	public synchronized StringBuffer append(int i){
		buf[size++]=(char)i;
		return this;
	}
}
